package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.config.WxPayV3Config;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.PaymentFeignClient;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.CloseOrderRequest;
import io.swagger.v3.oas.models.media.UUIDSchema;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Service
@SuppressWarnings({"all"})
@RefreshScope
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;
	@Autowired
	private UserAccountMapper userAccountMapper;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;
	@Autowired
	private RabbitService rabbitService;
	@Value("${recharge.cancel}")
	private int ttl;
	@Autowired
	private PaymentFeignClient paymentFeignClient;
	@Autowired
	private RSAAutoCertificateConfig rsaAutoCertificateConfig;
	@Autowired
	private WxPayV3Config wxPayV3Config;


	/**
	 * 根据充值订单编号查询充值信息
	 * @param orderNo
	 * @return
	 */
	@Override
	public RechargeInfo getRechargeInfo(String orderNo) {
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(
				new LambdaQueryWrapper<RechargeInfo>()
						.eq(RechargeInfo::getOrderNo, orderNo)
		);
		return rechargeInfo;
	}

	/**
	 * 保存充值记录
	 * @param rechargeInfoVo
	 * @return {orderNo:"充值订单编号"}
	 */
	@Override
	public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
		//添加充值记录
		RechargeInfo rechargeInfo = new RechargeInfo();
		//获取用户id
		Long userId = AuthContextHolder.getUserId();
		rechargeInfo.setUserId(userId);
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());

		//生成充值流水号
		String orderNo = "CZ" + DateUtil.today().replaceAll("-","") + IdUtil.getSnowflakeNextId();
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfoMapper.insert(rechargeInfo);

		// 延迟关单
		rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER,
				MqConst.ROUTING_CANCEL_ORDER,rechargeInfo.getId(),ttl);

		return Map.of("orderNo",orderNo);
	}

	/**
	 * 	微信支付成功后，处理充值业务
	 * @param orderNo
	 * @return
	 */
	@Override
	public void rechargePaySuccess(String orderNo) {
		//根据充值流水号查询充值信息
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>()
				.eq(RechargeInfo::getOrderNo, orderNo));
		//判断充值状态：0901-未支付 0902-已支付 0903-已取消
		if(SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
			//将充值状态改为已支付
			rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
			//更新充值信息
			rechargeInfoMapper.updateById(rechargeInfo);

			//修改总金额和可用金额
			BigDecimal rechargeAmount = rechargeInfo.getRechargeAmount();
			int row = userAccountMapper.update(null,
					new LambdaUpdateWrapper<UserAccount>()
							.eq(UserAccount::getUserId, rechargeInfo.getUserId())
							.setSql("total_amount = total_amount + " + rechargeAmount)
							.setSql("available_amount = available_amount + " + rechargeAmount)
							.setSql("total_income_amount = total_income_amount + " + rechargeAmount));
			if(row == 0){
				throw new GuiguException(500, "充值失败！");
			}
			//增加账户变动日志
			userAccountService.saveUserAccountDetail(rechargeInfo.getUserId(),"充值",
					SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,rechargeAmount,orderNo);
		}

	}


	/**
	 * 查询用户充值记录
	 *
	 * @param page
	 * @param limit
	 * @return
	 */
	@Override
	public Page<UserAccountDetail> findUserRechargePage(Page<UserAccountDetail> iPage, Long userId) {
		Page<UserAccountDetail> result = userAccountDetailMapper.selectPage(iPage,
				new LambdaQueryWrapper<UserAccountDetail>()
						.eq(UserAccountDetail::getUserId, userId)
						.eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT)
						.select(UserAccountDetail::getOrderNo, UserAccountDetail::getTitle,
								UserAccountDetail::getTradeType, UserAccountDetail::getAmount));

		return result;
	}


	/**
	 * 查询用户消费记录
	 *
	 * @param page
	 * @param limit
	 * @return
	 */
	@Override
	public Page<UserAccountDetail> findUserConsumePage(Page<UserAccountDetail> iPage, Long userId) {
		Page<UserAccountDetail> result = userAccountDetailMapper.selectPage(iPage,
				new LambdaQueryWrapper<UserAccountDetail>()
						.eq(UserAccountDetail::getUserId, userId)
						.eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS)
						.select(UserAccountDetail::getOrderNo, UserAccountDetail::getTitle,
								UserAccountDetail::getTradeType, UserAccountDetail::getAmount));

		return result;
	}

	/**
	 * 充值服务 - 延迟关单
	 * @param rechargeId
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void cancelRecharge(Long rechargeId) {
		//根据id查询充值记录
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectById(rechargeId);
		if(rechargeInfo != null){
			//判断当前充值记录状态 充值状态：0901-未支付 0902-已支付 0903-已取消
			if(SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
				//如果还是未支付,则将状态改为已取消
				rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_CANCEL);
				//更新充值记录
				rechargeInfoMapper.updateById(rechargeInfo);

				//关闭第三方支付平台(微信支付)支付订单
				// 初始化服务
				JsapiService service = new JsapiService.Builder().config(rsaAutoCertificateConfig).build();
				//关闭订单
				CloseOrderRequest request = new CloseOrderRequest();
				//调用远程支付服务获取到paymentInfo
				PaymentInfo paymentInfo = paymentFeignClient.getOutOrderNo(SystemConstant.PAYMENT_TYPE_RECHARGE, rechargeInfo.getOrderNo()).getData();
				Assert.notNull(paymentInfo,"查询充值流水号:{}的支付信息为空",rechargeInfo.getOrderNo());

				request.setOutTradeNo(paymentInfo.getOutTradeNo());
				request.setMchid(wxPayV3Config.getMerchantId());

				service.closeOrder(request);
			}
		}
	}
}
